using Microsoft.AspNetCore.Mvc;
using RAG.Application.Services.Interfaces;
using RAG.Application.Dtos.Role;

namespace RAG.Api.Controllers;

[ApiController]
[Route("api/[controller]")]
public class RoleController : ControllerBase
{
    private readonly IRoleService _roleService;

    public RoleController(IRoleService roleService)
    {
        _roleService = roleService;
    }

    /// <summary>
    /// 获取所有角色
    /// </summary>
    [HttpGet]
    public async Task<ActionResult<IEnumerable<RoleDto>>> GetAllRoles()
    {
        try
        {
            var roles = await _roleService.GetAllRolesAsync();
            return Ok(roles);
        }
        catch (Exception ex)
        {
            return StatusCode(500, new { message = "获取角色列表失败", error = ex.Message });
        }
    }

    /// <summary>
    /// 根据ID获取角色
    /// </summary>
    [HttpGet("{id}")]
    public async Task<ActionResult<RoleDto>> GetRoleById(Guid id)
    {
        try
        {
            var role = await _roleService.GetRoleByIdAsync(id);
            if (role == null)
            {
                return NotFound(new { message = "角色不存在" });
            }

            return Ok(role);
        }
        catch (Exception ex)
        {
            return StatusCode(500, new { message = "获取角色失败", error = ex.Message });
        }
    }

    /// <summary>
    /// 根据角色名称获取角色
    /// </summary>
    [HttpGet("name/{roleName}")]
    public async Task<ActionResult<RoleDto>> GetRoleByName(string roleName)
    {
        try
        {
            var role = await _roleService.GetRoleByNameAsync(roleName);
            if (role == null)
            {
                return NotFound(new { message = "角色不存在" });
            }

            return Ok(role);
        }
        catch (Exception ex)
        {
            return StatusCode(500, new { message = "获取角色失败", error = ex.Message });
        }
    }

    /// <summary>
    /// 创建角色
    /// </summary>
    [HttpPost]
    public async Task<ActionResult<RoleDto>> CreateRole([FromBody] RoleDto roleDto)
    {
        try
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var createdRole = await _roleService.CreateRoleAsync(roleDto);
            return CreatedAtAction(nameof(GetRoleById), new { id = createdRole.Id }, createdRole);
        }
        catch (InvalidOperationException ex)
        {
            return BadRequest(new { message = ex.Message });
        }
        catch (Exception ex)
        {
            return StatusCode(500, new { message = "创建角色失败", error = ex.Message });
        }
    }

    /// <summary>
    /// 更新角色
    /// </summary>
    [HttpPut("{id}")]
    public async Task<ActionResult<RoleDto>> UpdateRole(Guid id, [FromBody] RoleDto roleDto)
    {
        try
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var updatedRole = await _roleService.UpdateRoleAsync(id, roleDto);
            return Ok(updatedRole);
        }
        catch (InvalidOperationException ex)
        {
            return BadRequest(new { message = ex.Message });
        }
        catch (Exception ex)
        {
            return StatusCode(500, new { message = "更新角色失败", error = ex.Message });
        }
    }

    /// <summary>
    /// 删除角色
    /// </summary>
    [HttpDelete("{id}")]
    public async Task<ActionResult> DeleteRole(Guid id)
    {
        try
        {
            var result = await _roleService.DeleteRoleAsync(id);
            if (!result)
            {
                return NotFound(new { message = "角色不存在" });
            }

            return NoContent();
        }
        catch (InvalidOperationException ex)
        {
            return BadRequest(new { message = ex.Message });
        }
        catch (Exception ex)
        {
            return StatusCode(500, new { message = "删除角色失败", error = ex.Message });
        }
    }

    /// <summary>
    /// 为角色分配权限
    /// </summary>
    [HttpPost("{id}/permissions")]
    public async Task<ActionResult> AssignPermissionsToRole(Guid id, [FromBody] List<string> permissionNames)
    {
        try
        {
            var result = await _roleService.AssignPermissionsToRoleAsync(id, permissionNames);
            if (!result)
            {
                return NotFound(new { message = "角色不存在" });
            }

            return Ok(new { message = "权限分配成功" });
        }
        catch (Exception ex)
        {
            return StatusCode(500, new { message = "分配权限失败", error = ex.Message });
        }
    }

    /// <summary>
    /// 从角色移除权限
    /// </summary>
    [HttpDelete("{id}/permissions")]
    public async Task<ActionResult> RemovePermissionsFromRole(Guid id, [FromBody] List<string> permissionNames)
    {
        try
        {
            var result = await _roleService.RemovePermissionsFromRoleAsync(id, permissionNames);
            if (!result)
            {
                return NotFound(new { message = "角色不存在" });
            }

            return Ok(new { message = "权限移除成功" });
        }
        catch (Exception ex)
        {
            return StatusCode(500, new { message = "移除权限失败", error = ex.Message });
        }
    }
} 